﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Data.SqlClient;

namespace Nivdal.AuxCode
{
    public class GlobalFunctions
    {

        public bool IsAllowedLive(Object CanAddToLive)
        {

            if ((CanAddToLive.ToString() == "True") && (HttpContext.Current.User.Identity.IsAuthenticated))
                return true;
            else
                return false;
        }

        public static string EditorHelp()
        {
            return Resources.Resource.Global_EditorHelp.Replace("\r\n", "<br /> ").Replace("\n", "<br /> ");
        }

        public static string Between(string Text, string FirstString, string LastString)
        {
            string STR = Text;
            string STRFirst = FirstString;
            string STRLast = LastString;
            string FinalString;
            if (STR.Contains("http://youtu.be/"))
                FinalString = "http://www.youtube.com/v/" + STR.Substring(16, STR.Length - 16);
            else
            {

                int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
                string STRMid = STR.Substring(Pos1 + 1);
                int Pos2 = STRMid.IndexOf(LastString);
                if (Pos2 == -1)
                    Pos2 = Text.Length - Pos1 - 1;
                FinalString = "http://www.youtube.com/v/" + STR.Substring(Pos1, Pos2 + 1);
            }
            return FinalString;
        }

        public static bool IsNivdalLink(String s)
        {
            string[] NivdalLinkprefixes = { "Player.aspx?Id=", "MatchPage.aspx?MatchId=", "TeamHomePage.aspx?TeamId=",
                                            "League.aspx?LeagueId=", "coach.aspx?Id=", "UserPage.aspx?Id=",
                                            "Story.aspx?StoryId=", "NationalTeam.aspx?Id=",
                                            "ForumDetails.aspx?Id=", "ThreadDetails.aspx?ThreadId=",
                                            "www.nivdal.com/", "http://www.nivdal.com/", "http://nivdal.com/" };
            bool result = NivdalLinkprefixes.Any(prefix => s.StartsWith(prefix)); // first check if the string begins with nivdal url, if not check the other url and put target = blank
            return result;
        }

        public static bool IsYouTubeLink(String s)
        {
            string[] YouTubeLinkprefixes = { "www.youtube.com", "http://www.youtube.com", "http://youtu.be/" };
            bool result = YouTubeLinkprefixes.Any(prefix => s.StartsWith(prefix));
            return result;
        }

        public static bool IsWWWLink(String s)
        {
            string[] OtherLinkprefixes = { "www.", "http://" };
            bool result = OtherLinkprefixes.Any(prefix => s.StartsWith(prefix));
            return result;
        }

        public static string IsSmiley(String s)
        {
            string result = "";
            string[] face_smilePrefixes = { ":)", ":-)" };
            string[] smiley_sadPrefixes = { ":(", ":-(" };
            string[] emoticon_happyPrefixes = { ":D" };
            string[] emotion_tonguePrefixes = { ":p", ":P" };
            string[] smiley_redPrefixes = { ":$" };
            string[] smiley_confusePrefixes = { ":s", ":S" };
            string[] smiley_yellPrefixes = { ":@" };
            string[] smiley_OPrefixes = { ":o", ":O" };
            string[] smiley_WinkPrefixes = { ";)" };
            if (face_smilePrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/face_smile.png";
            else if (smiley_sadPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/smiley_sad.png";
            else if (emoticon_happyPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/emoticon_happy.png";
            else if (emotion_tonguePrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/emotion_tongue.png";
            else if (smiley_redPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/smiley_red.png";
            else if (smiley_confusePrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/smiley_confuse.png";
            else if (smiley_yellPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/smiley_yell.png";
            else if (smiley_OPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/stock_smiley.png";
            else if (smiley_WinkPrefixes.Any(prefix => s.StartsWith(prefix)))
                result = "/Images/Smiles/wink_smiley.png";
            return result;
        }

        public static String EncodeHtmlFromText(String Str)
        {
            string ImagePrefixStr = "<img src=\"";
           // string ImageSuffixStr = "\" width=\"120\" height=\"90\"  alt=\"Image\">";
            string ImageSuffixStr = "\" style=\"width:auto; height:auto; max-width:500px; max-height:500px;\"  alt=\"Image\" />";
            string LinkWWWPrefixStr = " <a href=\"";
            string LinkInternalPrefixStr = " <a href=\"";
            string LinkHTTPPrefixStr = " <a href=\"http://";
            string LinkSuffix1Str = "\" class=\"NewsItemStyle\">";
            string LinkSuffix2Str = "</a>";
            string YouTubePrefixStr = "<object width=\"425\" height=\"350\"><param name=\"movie\" value=\"";
            string YouTubeSuffix1Str = "\"></param><embed src=\"";
            string YouTubeSuffix2Str = "\" type=\"application/x-shockwave-flash\" width=\"425\" height=\"350\"></embed></object>";
            string BlankTargetLinkStr = "\" target=\"_blank";
            string SmileyPrefixLink = "<img src=\"";
            string SmileySuffixLink = "\" alt=\"smiley\" height=\"16\" width=\"16\" />";
            string AdditionalPrefix;
            CultureInfo ci; 
            ci = new CultureInfo("en-US");
            String Output = "";
            string f = Str;
            string ff = f.Replace("\r\n", " <br/> ").Replace("\n", " <br/> ");
            string[] split = ff.Split(new string[] { " " }, StringSplitOptions.None);
            foreach (string s in split)
            {
                if (s.Trim() != "")
                {
                    
                    if (s.EndsWith("jpg", true, ci) || s.EndsWith("gif", true, ci) || s.EndsWith("bmp", true, ci) || s.EndsWith("tif", true, ci) || s.EndsWith("png", true, ci) || s.EndsWith("jpeg", true, ci) )
                        Output = Output + ImagePrefixStr + s + ImageSuffixStr + " ";
                    else if (IsNivdalLink(s))
                    {
                        AdditionalPrefix = (s.StartsWith("http://") || s.StartsWith("www.")) ? LinkWWWPrefixStr : LinkInternalPrefixStr;
                        Output = Output + AdditionalPrefix + s + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                    }
                    else if (IsYouTubeLink(s))
                    {
                        String ytvi = Between(s, "v=", "&");
                        Output = Output + YouTubePrefixStr + ytvi + YouTubeSuffix1Str + ytvi + YouTubeSuffix2Str + " ";
                    }
                    else if (IsWWWLink(s))
                    {
                        if (s.StartsWith("www"))
                            Output = Output + LinkHTTPPrefixStr + s + BlankTargetLinkStr + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                        else if (s.StartsWith("http://"))
                            Output = Output + LinkWWWPrefixStr + s + BlankTargetLinkStr + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                    }
                    else if (IsSmiley(s) != "")
                    {
                        Output = Output + SmileyPrefixLink + IsSmiley(s) + SmileySuffixLink + " ";
                    }
                    else
                        Output = Output + s + " ";

                }

            }

            return Output;

        }

        public static String LightEncodeHtmlFromText(String Str)
        {
            string LinkSuffix1Str = "\" class=\"NewsItemStyle\">";
            string LinkSuffix2Str = "</a>";
            string BlankTargetLinkStr = "\" target=\"_blank";
            string SmileyPrefixLink = "<img src=\"";
            string LinkInternalPrefixStr = " <a href=\"";
            string SmileySuffixLink = "\" alt=\"smiley\" height=\"16\" width=\"16\" />";
            string LinkWWWPrefixStr = " <a href=\"";
            string LinkHTTPPrefixStr = " <a href=\"http://";
            CultureInfo ci;
            string AdditionalPrefix;
            ci = new CultureInfo("en-US");
            String Output = "";
            string f = Str;
            string ff = f.Replace("\r\n", " <br/> ").Replace("\n", " <br/> ");
            string[] split = ff.Split(new string[] { " " }, StringSplitOptions.None);
            foreach (string s in split)
            {
                if (s.Trim() != "")
                {
                    if (IsNivdalLink(s))
                    {
                        AdditionalPrefix = (s.StartsWith("http://") || s.StartsWith("www.")) ? LinkWWWPrefixStr : LinkInternalPrefixStr;
                        Output = Output + AdditionalPrefix + s + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                    }
                    else if (IsWWWLink(s))
                    {
                        if (s.StartsWith("www"))
                            Output = Output + LinkHTTPPrefixStr + s + BlankTargetLinkStr + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                        else if (s.StartsWith("http://"))
                            Output = Output + LinkWWWPrefixStr + s + BlankTargetLinkStr + LinkSuffix1Str + s + LinkSuffix2Str + " ";
                    }
                    else if (IsSmiley(s) != "")
                    {
                        Output = Output + SmileyPrefixLink + IsSmiley(s) + SmileySuffixLink + " ";
                    }
                    else
                        Output = Output + s + " ";

                }

            }

            return Output;

        }

        public static void GetStoryText(string StoryId, ref string OriginalText, ref string Text)
        {
            OriginalText = "";
            Text = "";
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("Nivdal_GetStoryText", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add("StoryId", System.Data.SqlDbType.Decimal, 12);
                cmd.Parameters["StoryId"].Value = StoryId;

                SqlDataReader reader;
                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                        while (reader.Read())
                        {
                            Text += reader.GetString(0);
                            OriginalText += reader.GetString(1);
                        }
                }
                catch (Exception ex) { Text = ex.Message; }
                finally
                {
                    conn.Close();
                }

            }
        }

        public static void AddStoryText(string storyId, string OriginalText, bool Edit)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            if (Edit)
            {                
                GND.ExecNivdalSQL("StoryId", "Nivdal_ClearStoryText", storyId);
            }
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                string Text = EncodeHtmlFromText(OriginalText);
                int TextPartNum = 0;
                while (Text.Length > 0 || OriginalText.Length > 0)
                { 
                    string TextPart = "", OriginalTextPart = "";

                    if (Text.Length > 4000)
                    {
                        TextPart = Text.Substring(0, 4000);
                        Text = Text.Substring(4000);
                    }
                    else 
                    {
                        TextPart = Text;
                        Text = "";
                    }

                    if (OriginalText.Length > 4000)
                    {
                        OriginalTextPart = OriginalText.Substring(0, 4000);
                        OriginalText = OriginalText.Substring(4000);
                    }
                    else
                    {
                        OriginalTextPart = OriginalText;
                        OriginalText = "";
                    }

                    GND.ExecNivdalSQL("StoryId", "PartNum", "Text", "OriginalText", "Nivdal_AddStoryPartNumber", 
                        storyId, TextPartNum.ToString(), TextPart, OriginalTextPart);

                    TextPartNum++;
                }
            }
        }
    }
}